"use client";
import { useState, useRef, useEffect } from "react";

interface Message {
  id: string;
  type: "user" | "agent";
  content: string;
  timestamp: Date;
  intent?: {
    type: string;
    confidence: number;
  };
  ticketId?: string;
}

export default function ServicePage() {
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [sessionId] = useState(() => `session-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const sendMessage = async () => {
    if (!input.trim() || loading) return;

    const userMessage: Message = {
      id: Date.now().toString(),
      type: "user",
      content: input,
      timestamp: new Date()
    };

    setMessages(prev => [...prev, userMessage]);
    const currentInput = input;
    setInput("");
    setLoading(true);

    try {
      const response = await fetch("/api/service", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ 
          message: currentInput, 
          sessionId 
        })
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.error || `HTTP ${response.status}`);
      }

      const result = await response.json();

      if (result.success) {
        const agentMessage: Message = {
          id: (Date.now() + 1).toString(),
          type: "agent",
          content: result.data.response,
          intent: result.data.intent,
          ticketId: result.data.ticketId || undefined,
          timestamp: new Date()
        };
        setMessages(prev => [...prev, agentMessage]);
      } else {
        throw new Error(result.error || "未知错误");
      }
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : "发生未知错误";
      const errorMsg: Message = {
        id: (Date.now() + 1).toString(),
        type: "agent",
        content: `❌ 错误：${errorMessage}`,
        timestamp: new Date()
      };
      setMessages(prev => [...prev, errorMsg]);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="max-w-4xl mx-auto h-screen flex flex-col">
      <div className="p-4 border-b bg-blue-50">
        <h1 className="text-2xl font-bold mb-2">AI 客服系统</h1>
        <p className="text-sm text-gray-600">会话ID: {sessionId}</p>
      </div>

      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {messages.length === 0 && (
          <div className="text-center text-gray-500 mt-20">
            <p className="text-lg mb-2">👋 欢迎使用 AI 客服系统</p>
            <p className="text-sm">我可以帮您：查询信息、处理投诉、接受建议</p>
            <p className="text-sm mt-2">试试问我："我想查询订单状态" 或 "我要投诉产品质量问题"</p>
          </div>
        )}

        {messages.map((message) => (
          <div key={message.id} className={`flex ${message.type === "user" ? "justify-end" : "justify-start"}`}>
            <div className={`max-w-3xl p-3 rounded-lg ${
              message.type === "user"
                ? "bg-blue-500 text-white"
                : "bg-gray-100"
            }`}>
              <div className="whitespace-pre-wrap">{message.content}</div>
              
              {message.intent && (
                <div className="mt-2 text-xs opacity-70">
                  意图: {message.intent.type} (置信度: {(message.intent.confidence * 100).toFixed(0)}%)
                </div>
              )}
              
              {message.ticketId && (
                <div className="mt-2 text-xs font-semibold text-orange-600">
                  🎫 已创建工单: {message.ticketId}
                </div>
              )}
              
              <div className="text-xs opacity-70 mt-1">
                {message.timestamp.toLocaleTimeString()}
              </div>
            </div>
          </div>
        ))}
        
        {loading && (
          <div className="flex justify-start">
            <div className="bg-gray-100 p-3 rounded-lg">
              <div className="flex items-center gap-2">
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-gray-900"></div>
                客服正在思考...
              </div>
            </div>
          </div>
        )}
        <div ref={messagesEndRef} />
      </div>

      <div className="p-4 border-t">
        <div className="flex gap-2">
          <input
            type="text"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyPress={(e) => e.key === "Enter" && sendMessage()}
            placeholder="输入您的问题..."
            className="flex-1 border rounded px-3 py-2"
            disabled={loading}
          />
          <button
            onClick={sendMessage}
            disabled={loading || !input.trim()}
            className="px-4 py-2 bg-blue-500 text-white rounded disabled:opacity-50"
          >
            发送
          </button>
        </div>
      </div>
    </div>
  );
}


